<?php
/**
 * 
 * Feed 类
 * @author will
 *
 */
class Feed {
	/**
	 * 获取好友的feed列表
	 * @param <array> $uins
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	public static function getList($uins , $offset = 0 , $limit = 10) {
		if(empty($uins)) return array();
		
		$Db = loadDB();
		
		$uins_str = implode(',' , $uins);
		
		$result = $Db->getAll("SELECT * FROM `feed` WHERE `uin` IN ({$uins_str}) ORDER BY `time` DESC LIMIT {$offset} , {$limit}");
		return empty($result) ? array() : $result;
	}
	
	/**
	 * 获取所有用户的feed列表
	 * @param <array> $uins
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	public static function getAllList($offset = 0 , $limit = 10) {
		$Db = loadDB();
		
		$result = $Db->getAll("SELECT * FROM `feed` ORDER BY `time` DESC LIMIT {$offset} , {$limit}");
		return empty($result) ? array() : $result;
	}
	
	/**
	 * 写心情feed
	 * @param <int> $uin
	 * @param <int> $status_id
	 * @param <string> $content
	 */
	public static function addStatus($uin , $status_id , $content) {
		return self::add($uin , $status_id , 'add_status' , array(
			'status_id' => $status_id,
			'content' => $content,
		));
	}
	
	/**
	 * 写普通内容型feed
	 * @param <int> $uin
	 * @param <string> $content
	 * @param <array> $urls
	 */
	public static function addContent($uin , $content , $type = 'normal' , $urls = array()) {
		return self::add($uin , time() , $type , array(
			'content' => $content,
			'urls' => $urls,
		));
	}

	/**
	 * 添加一条feed
	 * @param <int> $uin
	 * @param <string> $data_id
	 * @param <string> $type
	 * @param <array> $data
	 */
	protected static function add($uin , $data_id , $type , $data) {
		$Db = loadDB();
		
		$data = empty($data) ? array() : $data;
		$data = serialize($data);
		$time = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
		
		// 写入数据
		$insert_data = array(
			'uin' => $uin,
			'data_id' => $data_id,
			'type' => $type,
			'data' => $data,
			'time' => $time,
		);
		$success = $Db->doInsert('feed' , $insert_data);
		
		return $success ? 0 : 1001;
	}
	
	/**
	 * 删除一条feed
	 * @param <uin> $uin
	 * @param <string> $data_id
	 * @param <string> $type
	 */
	public static function delete($uin , $data_id , $type) {
		$Db = loadDB();
		
		$success = $Db->query("DELETE FROM `feed` WHERE `uin` = {$uin} , `data_id` = '{$data_id}' , `type` = '{$type}'");
		return $success ? 0 : 1002;
	}
	
	
	/**
	 * 格式化feed内容
	 * @param <array> $feed
	 */
	public static function formatContent($feed) {
		$content = htmlspecialchars($feed['content']);
		
		if(!empty($feed['urls'])) {
			$urls_str = '';
			foreach($feed['urls'] as $row) {
				$url = htmlspecialchars($row['url']) . '&amp;sid=' . sessionInfo('skey');
				$content .= '&nbsp; <a href="' . $url . '">' . $row['name'] . '</a>';
			}
		}
		
		return $content;
	}
	
}

# end of script
